﻿#include "pch.h"
#include "DelegateCommand.h"
#include "DelegateCommand.g.cpp"


namespace winrt::NovelReader::implementation
{
	DelegateCommand::DelegateCommand(
		winrt::NovelReader::ExecuteHandler const& executeHandler, winrt::NovelReader::CanExecuteHandler const& canExecuteHandler)
		: m_executeHandler{executeHandler}, m_canExecuteHandler {canExecuteHandler}
	{
	}


	winrt::event_token DelegateCommand::CanExecuteChanged(CanExecuteChangedHandler const& handler)
	{
		return m_canExecuteChanged.add(handler);
	}

	void DelegateCommand::CanExecuteChanged(winrt::event_token const& token) noexcept
	{
		m_canExecuteChanged.remove(token);
	}

	bool DelegateCommand::CanExecute(winrt::Windows::Foundation::IInspectable const& parameter)
	{
		if (m_canExecuteHandler != nullptr) {
			auto newValue = m_canExecuteHandler(parameter); 
			if (newValue != m_canExecute) {
				m_canExecute = newValue; 
			}
		}
		return m_canExecute; 
	}

	void DelegateCommand::Execute(winrt::Windows::Foundation::IInspectable const& parameter)
	{
		if (m_executeHandler != nullptr) {
			m_executeHandler(parameter); 
		}
	}
}
